<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Modal 登录弹窗单例</title>
</head>
<style>
    #modal {
        height: 400px;
        width: 600px;
        line-height: 400px;
        position: fixed;
        top: 20%;
        left: 30%;
        transform: -50% -50%;
        border: 1px solid #010101;
        text-align: center;
        border-radius: 10px;
        font-weight: 1000;
        font-size: 40px;
        background: linear-gradient(45deg, rgb(255, 132, 105) 30%, aqua 95%);
        -webkit-background-clip: text;
        background-clip: text;
        color: transparent;
    }
</style>

<body>
    <!-- <button id="open" style="display: none;">打开弹窗</button>  -->
    <!-- 不管用不用都会加载 -->
    <button id="open">打开弹窗</button>
    <button id="close">关闭弹窗</button>
    <button id="open2">打开天窗</button>

    <script>
        //DOM 推迟到登录的时候加载  -->  单例模式
        //登录时是登录弹窗，退出时是退出弹窗
        const Modal = (function () { //这是立即执行函数
            let modal = null; //定义一个自由变量，用来存储弹窗
            return function () {
                if (!modal) {  //只执行第一次和唯一一次
                    modal = document.createElement('div')
                    modal.innerHTML = '看哪, 这里竟然有一个弹窗！'
                    modal.id = 'modal'
                    modal.style.display = 'none'
                    document.body.appendChild(modal)
                }
                return modal
            }
        })()
        document.getElementById('open').addEventListener('click', function () {
            const modal = new Modal()
            modal.style.display = 'block'
        })
        document.getElementById('open2').addEventListener('click', function () {
            const modal = new Modal()
            modal.style.display = 'block'
        })
        document.getElementById('close').addEventListener('click', function () {
            const modal = new Modal()
            modal.style.display = 'none'
        })
        // new Modal() 不能，也没有必要new
    </script>
</body>

</html>